<template>
	<view class="form-item" :class="{required:rule.required}">
		<view class="form-item-label">{{label}}</view>
		<view class="form-item-content">
			<slot slot :rule="rule"></slot>
		</view>
		<view class="error" v-if="isErr">{{msg}}</view>
	</view>
</template>

<script>
	function getNestedProperty(obj, path) {
	    return path.split('.').reduce((acc, curr) => {
	        if (acc && acc.hasOwnProperty(curr)) {
	            return acc[curr];
	        } else {
	            return undefined;
	        }
	    }, obj);
	}
	export default {
		name: "AFormItem",
		options: {
			multipleSlots: true,
			styleIsolation: "isolated",
			addGlobalClass: true,
			virtualHost: true,
		},
		props: {
			label: String, //展示名
			prop: String, //属性名
			required: Boolean, //是否必填
			error: String, //校验错误提示信息，存在是进行简单校验（是否有值）
		},
		computed: {
			//找到AForm组件
			formComponent(){
				let Component = this;
				do{
					Component = Component.$parent;
				} while(Component && Component.$options.name != 'AForm')
				return Component
			},
			rule() {
				if(!this.formComponent) return {}
				let rule = this.formComponent.rulesData[this.prop]
				let { required, message, trigger, validator } = rule||{}
				
				return {
					required: required || this.required,
					disabled: this.formComponent.disabled,
					trigger: trigger|| 'blur'
				}
			},
		},
		
		data() {
			return {
				isErr: false, //校验报错
				msg: '', //报错信息展示
			}
		},
		methods:{
			//清空校验结果
			clearValidate(){
				this.isErr = false;
				this.msg = ''
			},
			validator(){
				let result = true
				let value = getNestedProperty(this.formComponent['form'],this.prop);
				let rules = this.formComponent.rulesData;
				let rule = rules[this.prop]
				let message = rule?.message || this.error ||`缺少${this.prop}的值`
				let validator = rule?.validator || ((rule, value, callback) => {
					if(rule||this.error) {
						if (value) callback()
						else callback(new Error(message))
					}
					else callback()
					
				})
				
				validator(rule, value, (error)=>{
					this.isErr = !!error
					this.msg = error && error.message
					result = !error
				})
				return result
			},
			//判断触发类型，并触发校验
			triggerValidate(type){
				if(this.rule.trigger.includes(type)) this.validator()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form-item {
		position: relative;
		padding: 20rpx 20rpx 40rpx 20rpx;
		display: flex;
		.form-item-label{
			flex-wrap: nowrap;
			flex-shrink: 0;
		}
		.form-item-content{
			background-color: #eee;
			margin-left: 10rpx;
			flex: 1;
		}
		&.required{
			.form-item-label{
				&::before{
					content:'*';
					color: red;
				}
			}
		}
		.error {
			color: red;
			position: absolute;
			bottom: 0;
			font-size: 30rpx;
			height: 40rpx;
			display: flex;
			align-items: center;
		}
	}
</style>